<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <!-- 页面标题 -->
        <div class="border-b border-gray-200 px-6 py-5">
          <h1 class="text-2xl font-bold text-gray-900">账号设置</h1>
          <p class="mt-1 text-sm text-gray-500">管理您的账号信息、安全设置和偏好</p>
        </div>

        <!-- 设置内容 -->
        <div class="flex flex-col md:flex-row">
          <!-- 左侧导航 -->
          <div class="w-full md:w-64 border-b md:border-b-0 md:border-r border-gray-200">
            <nav class="p-4">
              <ul class="space-y-1">
                <li v-for="(section, index) in settingSections" :key="index">
                  <button
                    @click="activeSection = section.id"
                    class="w-full flex items-center space-x-3 px-4 py-3 rounded-lg transition-colors duration-200"
                    :class="{
                      'bg-primary-50 text-primary-700': activeSection === section.id,
                      'text-gray-700 hover:bg-gray-50': activeSection !== section.id
                    }"
                  >
                    <UIcon :name="section.icon" class="h-5 w-5" :class="activeSection === section.id ? 'text-primary-600' : 'text-gray-500'" />
                    <span :class="activeSection === section.id ? 'font-medium' : ''">{{ section.name }}</span>
                  </button>
                </li>
              </ul>
            </nav>
          </div>

          <!-- 右侧内容 -->
          <div class="flex-1 p-6">
            <!-- 个人信息设置 -->
            <div v-if="activeSection === 'profile'" class="space-y-6">
              <h2 class="text-lg font-medium text-gray-900 pb-2 border-b border-gray-100">个人信息</h2>
              
              <UForm :state="profileForm" class="space-y-6" @submit="saveProfile">
                <!-- 用户名 -->
                <UFormGroup label="用户名" name="username">
                  <UInput v-model="profileForm.username" placeholder="您的用户名" disabled />
                  <template #hint>
                    <span class="text-xs text-gray-500">用户名创建后不可修改</span>
                  </template>
                </UFormGroup>

                <!-- 邮箱 -->
                <UFormGroup label="邮箱地址" name="email">
                  <UInput v-model="profileForm.email" placeholder="您的邮箱地址" />
                  <template #hint>
                    <span class="text-xs text-gray-500">用于接收通知和找回密码</span>
                  </template>
                </UFormGroup>

                <!-- 手机号 -->
                <UFormGroup label="手机号码" name="phone">
                  <UInput v-model="profileForm.phone" placeholder="您的手机号码" />
                  <template #hint>
                    <span class="text-xs text-gray-500">用于账号安全验证</span>
                  </template>
                </UFormGroup>

                <!-- 语言设置 -->
                <UFormGroup label="语言设置" name="language">
                  <USelect
                    v-model="profileForm.language"
                    :options="languageOptions"
                    placeholder="选择语言"
                  />
                </UFormGroup>

                <!-- 提交按钮 -->
                <div class="flex justify-end">
                  <UButton type="submit" color="primary">保存修改</UButton>
                </div>
              </UForm>
            </div>

            <!-- 账号安全设置 -->
            <div v-if="activeSection === 'security'" class="space-y-6">
              <h2 class="text-lg font-medium text-gray-900 pb-2 border-b border-gray-100">账号安全</h2>
              
              <!-- 修改密码 -->
              <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                <div class="flex items-center justify-between">
                  <div>
                    <h3 class="font-medium text-gray-900">修改密码</h3>
                    <p class="text-sm text-gray-500 mt-1">定期更新密码可以提高账号安全性</p>
                  </div>
                  <UButton color="primary" variant="soft" @click="showPasswordModal = true">修改</UButton>
                </div>
              </div>

              <!-- 两步验证 -->
              <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                <div class="flex items-center justify-between">
                  <div>
                    <h3 class="font-medium text-gray-900">两步验证</h3>
                    <p class="text-sm text-gray-500 mt-1">启用两步验证提高账号安全性</p>
                  </div>
                  <USwitch v-model="securityForm.twoFactorEnabled" @change="toggleTwoFactor" />
                </div>
              </div>

              <!-- 登录设备 -->
              <div class="mt-8">
                <h3 class="font-medium text-gray-900 mb-4">登录设备</h3>
                <div class="space-y-3">
                  <div v-for="(device, index) in loginDevices" :key="index" class="bg-white rounded-lg p-4 border border-gray-200 flex items-center justify-between">
                    <div class="flex items-center space-x-3">
                      <UIcon :name="device.icon" class="h-8 w-8 text-gray-500" />
                      <div>
                        <p class="font-medium text-gray-900">{{ device.name }}</p>
                        <p class="text-xs text-gray-500">{{ device.location }} · {{ device.lastActive }}</p>
                      </div>
                    </div>
                    <UButton v-if="device.current" color="gray" variant="ghost" size="sm" disabled>当前设备</UButton>
                    <UButton v-else color="red" variant="ghost" size="sm" @click="logoutDevice(device.id)">退出登录</UButton>
                  </div>
                </div>
              </div>
            </div>

            <!-- 通知设置 -->
            <div v-if="activeSection === 'notifications'" class="space-y-6">
              <h2 class="text-lg font-medium text-gray-900 pb-2 border-b border-gray-100">通知设置</h2>
              
              <div class="space-y-4">
                <div v-for="(notification, index) in notificationSettings" :key="index" class="flex items-center justify-between py-3 border-b border-gray-100">
                  <div>
                    <h3 class="font-medium text-gray-900">{{ notification.name }}</h3>
                    <p class="text-sm text-gray-500 mt-1">{{ notification.description }}</p>
                  </div>
                  <USwitch v-model="notification.enabled" @change="saveNotificationSettings" />
                </div>
              </div>
            </div>

            <!-- 隐私设置 -->
            <div v-if="activeSection === 'privacy'" class="space-y-6">
              <h2 class="text-lg font-medium text-gray-900 pb-2 border-b border-gray-100">隐私设置</h2>
              
              <div class="space-y-4">
                <div v-for="(privacy, index) in privacySettings" :key="index" class="flex items-center justify-between py-3 border-b border-gray-100">
                  <div>
                    <h3 class="font-medium text-gray-900">{{ privacy.name }}</h3>
                    <p class="text-sm text-gray-500 mt-1">{{ privacy.description }}</p>
                  </div>
                  <USelect
                    v-model="privacy.value"
                    :options="privacy.options"
                    size="sm"
                    class="w-32"
                    @change="savePrivacySettings"
                  />
                </div>
              </div>
            </div>

            <!-- 主题设置 -->
            <div v-if="activeSection === 'appearance'" class="space-y-6">
              <h2 class="text-lg font-medium text-gray-900 pb-2 border-b border-gray-100">主题与外观</h2>
              
              <!-- 主题选择 -->
              <div class="space-y-3">
                <h3 class="font-medium text-gray-700">主题模式</h3>
                <div class="grid grid-cols-3 gap-4">
                  <div
                    v-for="theme in themeOptions"
                    :key="theme.value"
                    class="border rounded-lg p-4 cursor-pointer transition-all duration-200"
                    :class="{
                      'border-primary-500 bg-primary-50': appearanceForm.theme === theme.value,
                      'border-gray-200 hover:border-gray-300': appearanceForm.theme !== theme.value
                    }"
                    @click="appearanceForm.theme = theme.value"
                  >
                    <div class="aspect-w-16 aspect-h-9 mb-3 rounded-md overflow-hidden" :class="theme.previewClass"></div>
                    <div class="text-center">
                      <p class="font-medium" :class="appearanceForm.theme === theme.value ? 'text-primary-700' : 'text-gray-700'">{{ theme.label }}</p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 字体大小 -->
              <div class="mt-6">
                <h3 class="font-medium text-gray-700 mb-3">字体大小</h3>
                <URange
                  v-model="appearanceForm.fontSize"
                  :min="12"
                  :max="20"
                  :step="1"
                />
                <div class="flex justify-between text-sm text-gray-500 mt-2">
                  <span>小</span>
                  <span>默认</span>
                  <span>大</span>
                </div>
              </div>

              <!-- 保存按钮 -->
              <div class="flex justify-end mt-6">
                <UButton color="primary" @click="saveAppearance">保存设置</UButton>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <UModal v-model="showPasswordModal">
      <div class="p-6">
        <h2 class="text-xl font-bold text-gray-900 mb-4">修改密码</h2>
        <UForm :state="passwordForm" class="space-y-4" @submit="changePassword">
          <UFormGroup label="当前密码" name="currentPassword">
            <UInput
              v-model="passwordForm.currentPassword"
              type="password"
              placeholder="输入当前密码"
            />
          </UFormGroup>
          <UFormGroup label="新密码" name="newPassword">
            <UInput
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="输入新密码"
            />
          </UFormGroup>
          <UFormGroup label="确认新密码" name="confirmPassword">
            <UInput
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="再次输入新密码"
            />
          </UFormGroup>
          <div class="flex justify-end space-x-3 mt-6">
            <UButton color="gray" variant="soft" @click="showPasswordModal = false">取消</UButton>
            <UButton type="submit" color="primary">确认修改</UButton>
          </div>
        </UForm>
      </div>
    </UModal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '~/utils/api'
import { auth } from '~/utils/auth'
// useToast will be auto-imported by Nuxt

// 激活的设置部分
const activeSection = ref('profile')

// 设置部分列表
const settingSections = [
  { id: 'profile', name: '个人信息', icon: 'i-heroicons-user-circle' },
  { id: 'security', name: '账号安全', icon: 'i-heroicons-shield-check' },
  { id: 'notifications', name: '通知设置', icon: 'i-heroicons-bell' },
  { id: 'privacy', name: '隐私设置', icon: 'i-heroicons-lock-closed' },
  { id: 'appearance', name: '主题外观', icon: 'i-heroicons-paint-brush' },
]

// 个人信息表单
const profileForm = ref({
  username: '',
  email: '',
  phone: '',
  language: 'zh-CN',
})

// 语言选项
const languageOptions = [
  { label: '简体中文', value: 'zh-CN' },
  { label: '繁體中文', value: 'zh-TW' },
  { label: 'English', value: 'en-US' },
  { label: '日本語', value: 'ja-JP' },
]

// 安全设置表单
const securityForm = ref({
  twoFactorEnabled: false,
})

// 密码修改表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 密码修改弹窗
const showPasswordModal = ref(false)

// 登录设备列表
const loginDevices = ref([
  {
    id: 1,
    name: 'MacBook Pro',
    icon: 'i-heroicons-computer-desktop',
    location: '上海',
    lastActive: '当前在线',
    current: true
  },
  {
    id: 2,
    name: 'iPhone 13',
    icon: 'i-heroicons-device-phone-mobile',
    location: '北京',
    lastActive: '2小时前',
    current: false
  },
  {
    id: 3,
    name: 'iPad Pro',
    icon: 'i-heroicons-device-tablet',
    location: '广州',
    lastActive: '昨天 14:30',
    current: false
  }
])

// 通知设置
const notificationSettings = ref([
  {
    name: '系统通知',
    description: '接收系统更新、维护和安全提醒',
    enabled: true
  },
  {
    name: '活动通知',
    description: '接收新活动、促销和特别优惠',
    enabled: true
  },
  {
    name: '消息通知',
    description: '接收新消息和回复提醒',
    enabled: true
  },
  {
    name: '邮件摘要',
    description: '接收每周活动和更新摘要邮件',
    enabled: false
  }
])

// 隐私设置
const privacySettings = ref([
  {
    name: '个人资料可见性',
    description: '控制谁可以查看您的个人资料',
    value: 'friends',
    options: [
      { label: '所有人', value: 'public' },
      { label: '仅好友', value: 'friends' },
      { label: '仅自己', value: 'private' }
    ]
  },
  {
    name: '搜索可见性',
    description: '控制是否可以通过搜索找到您',
    value: 'public',
    options: [
      { label: '所有人', value: 'public' },
      { label: '仅好友', value: 'friends' },
      { label: '关闭', value: 'off' }
    ]
  },
  {
    name: '活动状态',
    description: '显示您的在线状态',
    value: 'on',
    options: [
      { label: '开启', value: 'on' },
      { label: '关闭', value: 'off' }
    ]
  }
])

// 主题设置
const appearanceForm = ref({
  theme: 'light',
  fontSize: 16
})

// 主题选项
const themeOptions = [
  {
    label: '浅色模式',
    value: 'light',
    previewClass: 'bg-white border border-gray-200'
  },
  {
    label: '深色模式',
    value: 'dark',
    previewClass: 'bg-gray-900 border border-gray-700'
  },
  {
    label: '跟随系统',
    value: 'system',
    previewClass: 'bg-gradient-to-r from-white to-gray-900 border border-gray-300'
  }
]

// 初始化数据
onMounted(async () => {
  try {
    // 获取用户信息
    const user = await auth.getCurrentUser()
    if (user) {
      profileForm.value.username = user.username || ''
      profileForm.value.email = user.email || ''
      profileForm.value.phone = user.phone || ''
      profileForm.value.language = user.language || 'zh-CN'
      
      // 获取安全设置
      securityForm.value.twoFactorEnabled = user.twoFactorEnabled || false
      
      // 获取主题设置
      if (user.appearance) {
        appearanceForm.value.theme = user.appearance.theme || 'light'
        appearanceForm.value.fontSize = user.appearance.fontSize || 16
      }
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    useToast().add({
      title: '获取用户信息失败',
      description: '请稍后再试',
      color: 'red'
    })
  }
})

// 保存个人信息
const saveProfile = async () => {
  try {
    await api.post('/user/profile', profileForm.value)
    useToast().add({
      title: '保存成功',
      description: '个人信息已更新',
      color: 'green'
    })
  } catch (error) {
    console.error('保存个人信息失败', error)
    useToast().add({
      title: '保存失败',
      description: '请稍后再试',
      color: 'red'
    })
  }
}

// 切换两步验证
const toggleTwoFactor = async () => {
  try {
    await api.post('/user/security/two-factor', {
      enabled: securityForm.value.twoFactorEnabled
    })
    useToast().add({
      title: securityForm.value.twoFactorEnabled ? '已启用两步验证' : '已关闭两步验证',
      color: 'green'
    })
  } catch (error) {
    // 恢复原状态
    securityForm.value.twoFactorEnabled = !securityForm.value.twoFactorEnabled
    console.error('切换两步验证失败', error)
    useToast().add({
      title: '操作失败',
      description: '请稍后再试',
      color: 'red'
    })
  }
}

// 修改密码
const changePassword = async () => {
  // 验证密码
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    useToast().add({
      title: '密码不匹配',
      description: '新密码与确认密码不一致',
      color: 'red'
    })
    return
  }
  
  try {
    await api.post('/user/security/password', {
      currentPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.newPassword
    })
    
    // 重置表单并关闭弹窗
    passwordForm.value.currentPassword = ''
    passwordForm.value.newPassword = ''
    passwordForm.value.confirmPassword = ''
    showPasswordModal.value = false
    
    useToast().add({
      title: '密码修改成功',
      description: '请使用新密码登录',
      color: 'green'
    })
  } catch (error) {
    console.error('修改密码失败', error)
    useToast().add({
      title: '修改失败',
      description: '当前密码可能不正确',
      color: 'red'
    })
  }
}

// 退出设备登录
const logoutDevice = async (deviceId: number) => {
  try {
    await api.post('/user/security/logout-device', { deviceId })
    // 从列表中移除该设备
    loginDevices.value = loginDevices.value.filter(device => device.id !== deviceId)
    useToast().add({
      title: '已退出登录',
      description: '设备已成功退出登录',
      color: 'green'
    })
  } catch (error) {
    console.error('退出设备登录失败', error)
    useToast().add({
      title: '操作失败',
      description: '请稍后再试',
      color: 'red'
    })
  }
}

// 保存通知设置
const saveNotificationSettings = async () => {
  try {
    await api.post('/user/notifications/settings', { settings: notificationSettings.value })
    useToast().add({
      title: '通知设置已保存',
      color: 'green'
    })
  } catch (error) {
    console.error('保存通知设置失败', error)
    useToast().add({
      title: '保存失败',
      description: '请稍后再试',
      color: 'red'
    })
  }
}

// 保存隐私设置
const savePrivacySettings = async () => {
  try {
    await api.post('/user/privacy/settings', { settings: privacySettings.value })
    useToast().add({
      title: '隐私设置已保存',
      color: 'green'
    })
  } catch (error) {
    console.error('保存隐私设置失败', error)
    useToast().add({
      title: '保存失败',
      description: '请稍后再试',
      color: 'red'
    })
  }
}

// 保存主题设置
const saveAppearance = async () => {
  try {
    await api.post('/user/appearance', appearanceForm.value)
    // 应用主题设置
    document.documentElement.style.fontSize = `${appearanceForm.value.fontSize}px`
    // 应用主题模式
    if (appearanceForm.value.theme === 'dark') {
      document.documentElement.classList.add('dark')
    } else if (appearanceForm.value.theme === 'light') {
      document.documentElement.classList.remove('dark')
    }
    
    useToast().add({
      title: '主题设置已保存',
      color: 'green'
    })
  } catch (error) {
    console.error('保存主题设置失败', error)
    useToast().add({
      title: '保存失败',
      description: '请稍后再试',
      color: 'red'
    })
  }
}
</script>